import CryptoJS from 'crypto-js'

const fetchWithTimeout = async (url, options = {}, timeoutMs = 15000) => {
  const controller = new AbortController()
  const t = setTimeout(() => controller.abort(), timeoutMs)
  try {
    const res = await fetch(url, { ...options, signal: controller.signal })
    return res
  } finally {
    clearTimeout(t)
  }
}

const aesEncode = (str, key) => {
  key = CryptoJS.enc.Utf8.parse(key)
  const srcs = CryptoJS.enc.Utf8.parse(str)
  const encrypted = CryptoJS.AES.encrypt(srcs, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 })
  return encrypted.toString()
}

export const loginUseUsernameAndPassword = async (username, password) => {
  const secretkey = await fetch(`${process.env.GPO_ENDPOINT}/UserManagementApi/userFacadeApi/querySecretkey`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      username
    })
  })
  .then(async response=>{
    return (await response.json()).result
  })
  const encodePassword = aesEncode(password, secretkey)
  return await fetch(`${process.env.GPO_ENDPOINT}/UserManagementApi/userFacadeApi/internalUserLoginIn`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      username,
      password: encodePassword
    })
  })
  .then(response => response.json())
  .then(res => res.result)
}

export const checkSGSToken = async (sgsToken) => {
  return await fetch(`${process.env.GPO_ENDPOINT}/UserManagementApi/resource/querySystemResourceBySystemName/${sgsToken}?systemName=General%20Preorder`, {
    method: 'GET'
  }).then(res => res.json())
}

export const getOrderId = async (orderNo, sgsToken = '') => {
  try {
    console.log(`调用getOrderId API: orderNo=${orderNo}, sgsToken=${sgsToken ? '已提供' : '未提供'}`)
    
    // 检查是否有SGS Token
    if (!sgsToken) {
      console.warn(`警告: 未提供SGS Token，可能导致查询失败`)
    }
    
    const headers = {
      'Content-Type': 'application/json',
      'Productlinecode': 'HL',
    }
    if (sgsToken) {
      headers['Sgstoken'] = sgsToken
    }
    
    // 基于错误分析，尝试更多查询方式
    const queryMethods = [
      // 方式1: 使用suffixOrderNo参数查询（参考getEnquiryId成功模式）
      {
        name: 'suffixOrderNo查询',
        method: 'POST',
        url: `${process.env.GPO_ENDPOINT}/gpo-api/orderSearch/queryOrderList`,
        body: {
          'suffixOrderNo': orderNo,
          'page': 1,
          'rows': 10
        },
        requiresToken: true
      },
      // 方式2: 使用orderNo参数查询
      {
        name: 'orderNo参数查询',
        method: 'POST',
        url: `${process.env.GPO_ENDPOINT}/gpo-api/orderSearch/queryOrderList`,
        body: {
          'orderNo': orderNo,
          'productLineCode': 'HL',
          'page': 1,
          'rows': 10
        },
        requiresToken: true
      },
      // 方式3: 尝试order/page接口（GET方式）
      {
        name: 'order/page接口查询',
        method: 'GET',
        url: `${process.env.GPO_ENDPOINT}/gpo-api/order/page`,
        params: {
          'orderNo': orderNo,
          'page': 1,
          'rows': 10
        },
        requiresToken: true
      },
      // 方式4: 使用完整参数查询
      {
        name: '完整参数查询',
        method: 'POST',
        url: `${process.env.GPO_ENDPOINT}/gpo-api/orderSearch/queryOrderList`,
        body: {
          'orderNo': orderNo,
          'suffixOrderNo': orderNo,
          'productLineCode': 'HL',
          'page': 1,
          'rows': 10
        },
        requiresToken: true
      },
      // 方式5: 简化suffixOrderNo查询
      {
        name: '简化suffixOrderNo查询',
        method: 'POST',
        url: `${process.env.GPO_ENDPOINT}/gpo-api/orderSearch/queryOrderList`,
        body: {
          'suffixOrderNo': orderNo
        },
        requiresToken: true
      },
      // 方式6: 尝试不同的参数组合
      {
        name: '不同参数组合查询',
        method: 'POST',
        url: `${process.env.GPO_ENDPOINT}/gpo-api/orderSearch/queryOrderList`,
        body: {
          'orderNumber': orderNo,
          'page': 1,
          'rows': 10
        },
        requiresToken: true
      }
    ]
    
    for (const method of queryMethods) {
      try {
        // 如果方法需要Token但没有提供，跳过
        if (method.requiresToken && !sgsToken) {
          console.log(`跳过${method.name}: 需要SGS Token但未提供`)
          continue
        }
        
        let url = method.url
        let fetchOptions = {
          method: method.method || 'POST',
          headers
        }
        
        if (method.method === 'GET' && method.params) {
          // GET请求，参数放在URL中
          const params = new URLSearchParams(method.params)
          url = `${url}?${params.toString()}`
          console.log(`尝试${method.name}: GET ${url}`)
        } else if (method.body) {
          // POST请求，参数放在body中
          fetchOptions.body = JSON.stringify(method.body)
          console.log(`尝试${method.name}: ${JSON.stringify(method.body)}`)
        }
        
        const response = await fetch(url, fetchOptions)
        const result = await response.json()
        console.log(`${method.name}响应:`, result)
        
        // 检查不同的响应格式
        if (result?.success) {
          // 检查分页格式响应
          if (result?.data?.list?.length > 0) {
            const orderId = result.data.list[0].orderId || result.data.list[0].id || result.data.list[0].objectId
            if (orderId) {
              console.log(`成功找到Order ID (${method.name}): ${orderId}`)
              return orderId
            }
          }
          // 检查数组格式响应
          if (Array.isArray(result?.data) && result.data.length > 0) {
            const orderId = result.data[0].orderId || result.data[0].id || result.data[0].objectId
            if (orderId) {
              console.log(`成功找到Order ID (${method.name}): ${orderId}`)
              return orderId
            }
          }
          // 检查直接返回ID的情况
          if (result?.data?.orderId || result?.data?.id || result?.data?.objectId) {
            const orderId = result.data.orderId || result.data.id || result.data.objectId
            console.log(`成功找到Order ID (${method.name}): ${orderId}`)
            return orderId
          }
          // 检查直接返回订单对象的情况
          if (result?.data && typeof result.data === 'object' && !Array.isArray(result.data)) {
            const orderId = result.data.orderId || result.data.id || result.data.objectId
            if (orderId) {
              console.log(`成功找到Order ID (${method.name}): ${orderId}`)
              return orderId
            }
          }
        } else {
          console.log(`${method.name}失败: ${result?.message || '未知错误'}`)
        }
      } catch (methodError) {
        console.error(`${method.name}异常:`, methodError)
        continue
      }
    }
    
    console.warn(`所有查询方式都未找到Order: ${orderNo}`)
    if (!sgsToken) {
      console.warn(`提示: 可能需要有效的SGS Token才能查询订单信息`)
    }
    return null
  } catch (error) {
    console.error(`getOrderId API调用失败:`, error)
    return null
  }
}

export const getOrderDetail = async (orderId, sgsToken = '') => {
  try {
    console.log(`调用getOrderDetail API: orderId=${orderId}`)
    const headers = {}
    if (sgsToken) {
      headers['Sgstoken'] = sgsToken
    }
    
    const response = await fetch(`${process.env.GPO_ENDPOINT}/gpo-api/order/HL/detail?orderId=${orderId}`, {
      method: 'GET',
      headers
    })
    
    const result = await response.json()
    console.log(`getOrderDetail API响应:`, result)
    
    if (result?.success) {
      return result.data
    }
    return null
  } catch (error) {
    console.error(`getOrderDetail API调用失败:`, error)
    return null
  }
}

export const getSampleDataByOrderId = async (orderId, sgsToken = '') => {
  try {
    console.log(`调用getSampleDataByOrderId API: orderId=${orderId}`)
    const headers = {}
    if (sgsToken) {
      headers['Sgstoken'] = sgsToken
    }
    
    const response = await fetch(`${process.env.GPO_ENDPOINT}/gpo-api/order/productSample/HL/detail/${orderId}`, {
      method: 'GET',
      headers
    })
    
    const result = await response.json()
    console.log(`getSampleDataByOrderId API响应:`, result)
    
    if (result?.success) {
      return result.data
    }
    return null
  } catch (error) {
    console.error(`getSampleDataByOrderId API调用失败:`, error)
    return null
  }
}

export const saveOrderDetail = async (body) => {
  return await fetch(`${process.env.GPO_ENDPOINT}/gpo-api/order/HL/saveOrderInfo`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(body)
  })
  .then(res => res.json())
}

export const saveCurrentLab = async (labCode, sgsToken) => {
  return await fetch(`${process.env.GPO_ENDPOINT}/UserManagementApi/login/saveCurrentLab`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Sgstoken': sgsToken,
    },
    body: JSON.stringify({
      "sgsToken": sgsToken,
      "systemID": "829f35009d354a9ca8addbdf83080c76",
      "resouceID": null,
      "labCode": labCode
    })
  })
  .then(res => res.json())
}

export const getEnquiryId = async (enquiryOrderNo) => {
  const url = `${process.env.GPO_ENDPOINT}/gpo-micro-api/ai/tool/query-dff-template`;
  const payload = {
    'objectType': "Enquiry",
    'objectNo': enquiryOrderNo,
    'productLineCode': "HL"
  };

  console.log(`[getEnquiryId] Request URL: ${url}`);
  console.log(`[getEnquiryId] Request Payload: ${JSON.stringify(payload, null, 2)}`);

  try {
    const response = await fetchWithTimeout(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Productlinecode': 'HL',
      },
      body: JSON.stringify(payload)
    }, 15000);

    const responseBody = await response.text();
    console.log(`[getEnquiryId] Response Status: ${response.status}`);
    console.log(`[getEnquiryId] Response Body: ${responseBody}`);

    if (!response.ok) {
      throw new Error(`API request failed with status ${response.status}`);
    }

    let result
    try {
      result = JSON.parse(responseBody)
    } catch {
      result = null
    }

    if (result?.success && result?.data?.productTemplateId) {
      const enquiryId = result.data.productTemplateId;
      console.log(`[getEnquiryId] Successfully found Enquiry ID (from productTemplateId): ${enquiryId}`);
      return enquiryId;
    }

    console.warn(`[getEnquiryId] Enquiry not found for: ${enquiryOrderNo}`);
    return null;
  } catch (error) {
    console.error(`[getEnquiryId] API call failed:`, error);
    return null;
  }
}

export const getEnquiryDetail = async (enquiryId, sgsToken = '') => {
  try {
    console.log(`调用getEnquiryDetail API: enquiryId=${enquiryId}`)
    const response = await fetch(`${process.env.GPO_ENDPOINT}/gpo-api/enquiry/detail?sgsToken=${sgsToken}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Productlinecode': 'HL',
      },
      body: JSON.stringify({
        'enquiryId': enquiryId,
        'productLine': 'HL'
      })
    })
    
    const result = await response.json()
    console.log(`getEnquiryDetail API响应:`, result)
    
    if (result?.success) {
      return result.data
    }
    return null
  } catch (error) {
    console.error(`getEnquiryDetail API调用失败:`, error)
    return null
  }
}

export const getSampleDataByEnquiryId = async (enquiryId, sgsToken = '') => {
  try {
    console.log(`调用getSampleDataByEnquiryId API: enquiryId=${enquiryId}`)
    const headers = {
      'Productlinecode': 'HL',
    }
    if (sgsToken) {
      headers['Sgstoken'] = sgsToken
    }
    
    const response = await fetch(`${process.env.GPO_ENDPOINT}/gpo-api/enquiry/product/sample?enquiryId=${enquiryId}`, {
      method: 'GET',
      headers,
    })
    
    const result = await response.json()
    console.log(`getSampleDataByEnquiryId API响应:`, result)
    
    if (result?.success) {
      return result.data
    }
    return null
  } catch (error) {
    console.error(`getSampleDataByEnquiryId API调用失败:`, error)
    return null
  }
}

export const saveEnquiryDetail = async (body, sgsToken) => {
  return await fetch(`${process.env.GPO_ENDPOINT}/gpo-api/enquiry/save`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Sgstoken': sgsToken,
      'Productlinecode': 'HL',
    },
    body: JSON.stringify(body)
  })
  .then(res => res.json())
}

export const getUserLabBuInfo = async (sgsToken) => {
  try {
    // console.log(`调用getUserLabBuInfo API: sgsToken=${sgsToken ? '已提供' : '未提供'}`)
    
    const response = await fetch(`${process.env.GPO_ENDPOINT}/gpo-api/userInfo/getUserLabBuInfo`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Sgstoken': sgsToken,
      },
      body: JSON.stringify({
        sgsToken: sgsToken
      })
    })
    
    const result = await response.json()
    console.log(`getUserLabBuInfo API响应:`, result)
    
    // 检查响应结构，直接返回数据而不检查success字段
    if (result && typeof result === 'object') {
      // 如果result有success字段且为true，返回data
      if (result.success === true && result.data) {
        console.log('✓ API响应成功，返回data字段:', result.data)
        return result.data
      }
      // 如果result本身就是用户数据（没有success字段包装）
      else if (result.locationName || result.labCode || result.labName) {
        // console.log('✓ API直接返回用户数据:', result)
        return result
      }
      // 如果有其他可能的数据结构
      else {
        console.log('API响应结构分析:', {
          hasSuccess: 'success' in result,
          successValue: result.success,
          hasData: 'data' in result,
          dataValue: result.data,
          hasLocationName: 'locationName' in result,
          resultKeys: Object.keys(result)
        })
      }
    }
    
    console.warn('getUserLabBuInfo: 无法从API响应中提取用户数据')
    return null
  } catch (error) {
    console.error(`getUserLabBuInfo API调用失败:`, error)
    return null
  }
}

export const queryCustomer = async ({
  buCode,
  locationCode,
  customerNameCn,
  customerGroupName,
  displayType,
  code,
  contactRole
}) => {
  const formData = new FormData()
  formData.append('buCode', buCode)
  formData.append('locationCode', locationCode)
  if (customerNameCn) formData.append('customerNameCn', customerNameCn)
  if (customerGroupName) formData.append('customerGroupName', customerGroupName)
  if (displayType) formData.append('displayType', displayType)
  if (code) formData.append('code', code)
  if (contactRole) formData.append('contactRole', contactRole)

  return await fetch(`${process.env.GPO_ENDPOINT}/CustomerApi/preOrderCustomer/contactAddress/query`, {
    method: 'POST',
    body: formData
  })
  .then(res => res.json())
  .then(res => res?.rows)
}

// 更新Order的DFF字段
export const updateOrderDff = async (dffData, sgsToken) => {
  try {
    console.log(`更新Order DFF字段: ${dffData.objectNo}`)
    
    // 首先获取Order ID
    const orderId = await getOrderId(dffData.objectNo, sgsToken)
    if (!orderId) {
      throw new Error(`无法找到订单: ${dffData.objectNo}`)
    }
    
    // 构建DFF更新请求数据
    const updateData = {
      orderId: orderId,
      dffFields: dffData.dffFields
    }
    
    const headers = {
      'Content-Type': 'application/json',
      'Productlinecode': dffData.productLineCode || 'HL'
    }
    
    if (sgsToken) {
      headers['Sgstoken'] = sgsToken
    }
    
    const response = await fetch(`${process.env.GPO_ENDPOINT}/gpo-api/order/updateDff`, {
      method: 'POST',
      headers: headers,
      body: JSON.stringify(updateData)
    })
    
    if (!response.ok) {
      throw new Error(`HTTP错误: ${response.status} ${response.statusText}`)
    }
    
    const result = await response.json()
    console.log('Order DFF更新结果:', result)
    
    return result
    
  } catch (error) {
    console.error('更新Order DFF字段时出错:', error)
    throw error
  }
}

// 更新Enquiry的DFF字段
export const updateEnquiryDff = async (dffData, sgsToken) => {
  try {
    console.log(`更新Enquiry DFF字段: ${dffData.objectNo}`)
    
    // 首先获取Enquiry ID
    const enquiryId = await getEnquiryId(dffData.objectNo, sgsToken)
    if (!enquiryId) {
      throw new Error(`无法找到询价单: ${dffData.objectNo}`)
    }
    
    // 构建DFF更新请求数据
    const updateData = {
      enquiryId: enquiryId,
      dffFields: dffData.dffFields
    }
    
    const headers = {
      'Content-Type': 'application/json',
      'Productlinecode': dffData.productLineCode || 'HL'
    }
    
    if (sgsToken) {
      headers['Sgstoken'] = sgsToken
    }
    
    const response = await fetch(`${process.env.GPO_ENDPOINT}/gpo-api/enquiry/updateDff`, {
      method: 'POST',
      headers: headers,
      body: JSON.stringify(updateData)
    })
    
    if (!response.ok) {
      throw new Error(`HTTP错误: ${response.status} ${response.statusText}`)
    }
    
    const result = await response.json()
    console.log('Enquiry DFF更新结果:', result)
    
    return result
    
  } catch (error) {
    console.error('更新Enquiry DFF字段时出错:', error)
    throw error
  }
}
